package login

import (
	"context"
	v1 "donkey-admin/api/apis/v1"
	"donkey-admin/internal/consts"
	"donkey-admin/internal/dao"
	"donkey-admin/internal/model/do"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gmeta"
	"github.com/google/uuid"
	"reflect"
)

func (s *sApi) ApisSyncToCache(ctx context.Context, req *v1.ApiSyncToCacheReq) (res *v1.ApiSyncToCacheRes, err error) {

	_, err = dao.SysApis.Ctx(ctx).Unscoped().Where("deleted_at", nil).Delete()
	if err != nil {
		g.Log().Error(ctx, err)
		return nil, err
	}

	routes := consts.Server.GetRoutes()
	for _, item := range routes {
		handler := item.Handler
		if handler.Info.Type != nil && handler.Info.Type.NumIn() == 2 {
			var objectReq = reflect.New(handler.Info.Type.In(1))

			_, err = dao.SysApis.Ctx(ctx).Insert(do.SysApis{
				Uuid:      uuid.New().String(),
				ApiPath:   item.Route,
				ApiMethod: item.Method,
				ApiInfo:   gmeta.Get(objectReq, "summary").String(),
				ApiGroup:  gmeta.Get(objectReq, "tags").String(),
			})
			if err != nil {
				g.Log().Error(ctx, err)
			}

		}
	}
	return &v1.ApiSyncToCacheRes{}, nil
}
